// app.js
import './utils/addInterceptor'
const http = require('./utils/http')
const api = require('./utils/api')
let retryCount = 0

App({
  onLaunch() {
    this.calcNavBarInfo()
    this.calcTabBarInfo()
    this.initData() 
  },

  watch: function(key, method) {
		var obj = this.globalData;
		//加个前缀生成隐藏变量，防止死循环发生
		let ori = obj[key]; //obj[key]这个不能放在Object.defineProperty里
		if (ori) { //处理已经声明的变量，绑定处理
			method(ori);
		}
		Object.defineProperty(obj, key, {
			configurable: true,
			enumerable: true,
			set: function(value) {
				this['_' + key] = value;
				// console.log('是否会被执行2')
				method(value);
			},
			get: function() {
				// 在其他界面调用key值的时候，这里就会执行。
				if (typeof this['_' + key] == 'undefined') {
					if (ori) {
						//这里读取数据的时候隐藏变量和 globalData设置不一样，所以要做同步处理
						this['_' + key] = ori;
						return ori;
					} else {
						return undefined;
					}
				} else {
					return this['_' + key];
				}
			}
		})
	},
  globalData: {
    openId: 0,
    memberId: 0,
    selectStoreId: 0,
    //当前定位位置
    latitude: '',
    longitude: '',
    //全局数据管理
    navBarHeight: 0, // 导航栏高度
    menuBottom: 0, // 胶囊距底部间距（顶部间距也是这个）
    menuHeight: 0, // 胶囊高度
    screenHeight: 0,
    screenWidth: 0,
  },

  requestData(code, lati, long) {
    http.request({
      showLoading: true,
      url: api.login,
      method: 'POST',
      data: {
        clientEnum: '1',
        code: code,
        regionLatitude: lati,
        regionLongitude: long
      }
    }).then(res=>{
      console.log(res.data)
      this.globalData.openId = res.data.result.openId
      this.globalData.memberId = res.data.result.memberId
      this.globalData.selectStoreId = res.data.result.selectStoreId
      wx.setStorageSync('openId', res.data.result.openId)
      wx.setStorageSync('memberId', res.data.result.memberId)
      wx.setStorageSync('selectStoreId', res.data.result.selectStoreId)
    }).catch(err=>{
      console.log(err)
      if (retryCount < 3) {
        setTimeout(() => {
          this.initData()
          retryCount++
        }, 6000);
      }
    })
  },

  initData() {
    this.globalData.tel = wx.getStorageSync('tel')
    var openId = wx.getStorageSync('openId')
    var memberId = wx.getStorageSync('memberId')
    var selectStoreId = wx.getStorageSync('selectStoreId')
    console.log('openId', openId)
    if (openId == "" || openId == null || memberId == "" || memberId == null || selectStoreId == "" || selectStoreId == null) {
      wx.login({
        timeout: 6000,
        success:(res)=>{
          console.log(res)
          let code = res.code
          wx.getLocation({
            type: 'gcj02',
            success: (res) => {
              this.globalData.latitude = res.latitude
              this.globalData.longitude = res.longitude
              this.requestData(code, res.latitude, res.longitude)
            },
            fail:(res)=>{
              console.log('fail', res)
              this.globalData.latitude = 0
              this.globalData.longitude = 0
              this.requestData(code, 0, 0)
            }
          })
        }
      })
    }
    else {
      wx.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.globalData.latitude = res.latitude
          this.globalData.longitude = res.longitude
          this.globalData.openId = openId
          this.globalData.memberId = memberId
          this.globalData.selectStoreId = selectStoreId
        },
        fail:(res)=>{
          console.log('fail', res)
          this.globalData.latitude = 0
          this.globalData.longitude = 0
          this.globalData.openId = openId
          this.globalData.memberId = memberId
          this.globalData.selectStoreId = selectStoreId
        }
      })
    }
  },

  calcTabBarInfo() {
    const res = wx.getSystemInfoSync()
    const { screenHeight, screenWidth, safeArea: { bottom } } = res
    if (screenHeight && bottom){
      this.globalData.screenWidth = screenWidth
      this.globalData.screenHeight = screenHeight
      let safeBottom = screenHeight - bottom
      this.globalData.tabBarHeight = 48 + safeBottom
    }
  },

  /**
   * @description 计算导航栏信息
   */
  calcNavBarInfo () {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度 = 状态栏到胶囊的间距（胶囊上坐标位置-状态栏高度） * 2 + 胶囊高度 + 状态栏高度
    this.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
    // 状态栏和菜单按钮(标题栏)之间的间距
	// 等同于菜单按钮(标题栏)到正文之间的间距（胶囊上坐标位置-状态栏高度）
    this.globalData.menuBottom = menuButtonInfo.top - systemInfo.statusBarHeight;
    // 菜单按钮栏(标题栏)的高度
    this.globalData.menuHeight = menuButtonInfo.height;
  }
})
